package com.briup.pts.service.impl;


import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.FenceHouse;
import com.briup.pts.domain.vo.FenceWithHurdles;
import com.briup.pts.mapper.FenceHouseMapper;
import com.briup.pts.service.FenceHouseService;
import com.briup.pts.util.AssertUtil;
import com.briup.pts.util.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;


@RequiredArgsConstructor
@Service
public class FenceHouseServiceImpl implements FenceHouseService {
    private final FenceHouseMapper mapper;

    @Override
    public PageInfo<FenceHouse> pageQueryByCondition(Integer pageNum,
                                                        Integer pageSize, String fhName) {
        try (Page<FenceHouse> ignored = PageHelper.startPage(pageNum,pageSize)){
            List<FenceHouse> fences= mapper.queryPage(fhName);
            return new PageInfo<>(fences);
        }
    }

    @Override
    public FenceWithHurdles selectById(String fhId) {
        FenceWithHurdles fenceWithHurdles=mapper.selectById(fhId);
        // 如果根据id能够获取到数据，那么直接返回，
        // 如果获取不到数据，那么抛出异常表示该栏舍不存在
        return Optional.ofNullable(fenceWithHurdles)
                .orElseThrow(() -> new ServiceException(
                        ResultCode.FH_IS_NOT_EXISTS));
    }


    @Override
    public void saveOrUpdate(FenceHouse fenceHouse) {
        String fhId = fenceHouse.getFhId();
        if (StringUtils.hasText(fhId)) {
            FenceHouse fenceHouse1 = mapper.selectById(fhId);
            // 如果栏舍不存在，那么直接抛出异常
            AssertUtil.requiredNotNull(fenceHouse1,
                    ResultCode.FH_IS_NOT_EXISTS);
            // 表示修改，可以先删除数据，在新增数据
            mapper.deleteById(fhId);
        }else {
            // 新增数据，需要自己先使用UUID生成对应的ID
            String id = UuidUtil.randomUuid();
            fenceHouse.setFhId(id);
        }
        // 新增数据
        mapper.addFenceHouse(fenceHouse);
    }


    @Override
    public void deleteById(String fhId) {
        mapper.deleteById(fhId);
    }

    @Override
    public void deleteByIdAll(List<String> ids) {
        mapper.deleteByIdAll(ids);
    }
    }
